import { readdir, readFile, writeFile, stat } from "fs/promises"
import { join } from "path"

// Function to parse frontmatter from markdown content
function parseFrontmatter(content) {
  const frontmatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/
  const match = content.match(frontmatterRegex)

  if (!match) {
    throw new Error("No frontmatter found in markdown file")
  }

  const frontmatterText = match[1]
  const markdownContent = match[2]

  // Parse YAML-like frontmatter
  const frontmatter = {}
  const lines = frontmatterText.split("\n")

  for (const line of lines) {
    const trimmed = line.trim()
    if (!trimmed) continue

    if (trimmed.startsWith("tags:")) {
      // Handle tags array
      const tagsMatch = trimmed.match(/tags:\s*\[(.*)\]/)
      if (tagsMatch) {
        frontmatter.tags = tagsMatch[1].split(",").map((tag) => tag.trim().replace(/['"]/g, ""))
      }
    } else {
      // Handle other fields
      const colonIndex = trimmed.indexOf(":")
      if (colonIndex > 0) {
        const key = trimmed.substring(0, colonIndex).trim()
        const value = trimmed
          .substring(colonIndex + 1)
          .trim()
          .replace(/['"]/g, "")
        frontmatter[key] = value
      }
    }
  }

  return { frontmatter, content: markdownContent }
}

// Function to generate slug from filename
function generateSlug(relativePath) {
  // Convert backslashes to forward slashes and remove .md extension
  const pathWithoutExtension = relativePath.replace(/\\/g, "/").replace(/\.md$/i, "")

  return pathWithoutExtension
    .split("/")
    .map((segment) => {
      // URL encode the segment to handle Chinese characters properly
      return encodeURIComponent(segment)
    })
    .join("/")
}

// Function to process Obsidian-style image links
function processObsidianImages(content) {
  // Convert Obsidian-style image links: ![[image.png]] to standard Markdown format
  return content.replace(/!\[\[([^\[\]]+)\]\]/g, (match, imagePath) => {
    // Trim whitespace and normalize path
    const trimmedPath = imagePath.trim();
    
    // Use /images/ directory in public folder
    const fullImagePath = `/images/${trimmedPath}`;
    
    // Return standard Markdown image syntax with URL-encoded path
    return `![${trimmedPath}](${encodeURI(fullImagePath)})`;
  });
}

// Function to escape content for JavaScript string
function escapeContent(content) {
  return content.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\${/g, "\\${")
}

async function findMarkdownFiles(dir, basePath = "") {
  const files = []
  const entries = await readdir(dir)

  for (const entry of entries) {
    const fullPath = join(dir, entry)
    const stats = await stat(fullPath)

    if (stats.isDirectory()) {
      // Recursively search subdirectories - now properly handles Chinese characters
      const subFiles = await findMarkdownFiles(fullPath, join(basePath, entry))
      files.push(...subFiles)
    } else if (entry.toLowerCase().endsWith(".md")) {
      files.push({
        filename: entry,
        fullPath,
        relativePath: basePath ? join(basePath, entry) : entry,
        category: basePath || "未分类", // Chinese characters fully supported in category names
      })
    }
  }

  return files
}

async function generateBlogPosts() {
  try {
    console.log("[v0] Starting blog posts generation...")

    const postsDir = "content/posts"
    const markdownFiles = await findMarkdownFiles(postsDir)

    console.log(`[v0] Found ${markdownFiles.length} markdown files in directories`)

    const blogPosts = []

    // Process each markdown file
    for (const fileInfo of markdownFiles) {
      console.log(`[v0] Processing ${fileInfo.relativePath}...`)

      const fileContent = await readFile(fileInfo.fullPath, "utf-8")

      try {
        const { frontmatter, content } = parseFrontmatter(fileContent)
        const slug = generateSlug(fileInfo.relativePath)

        // Process Obsidian-style images before escaping content
        const processedContent = processObsidianImages(content.trim());
        
        // Create blog post object
        const blogPost = {
          slug,
          title: frontmatter.title || "Untitled",
          excerpt: frontmatter.excerpt || "",
          date: frontmatter.date || new Date().toISOString().split("T")[0],
          readTime: frontmatter.readTime || "5 分钟阅读",
          category: frontmatter.category || fileInfo.category,
          tags: frontmatter.tags || [],
          content: escapeContent(processedContent),
        }

        blogPosts.push(blogPost)
        console.log(`[v0] Successfully processed ${fileInfo.relativePath}`)
      } catch (error) {
        console.error(`[v0] Error processing ${fileInfo.relativePath}:`, error.message)
      }
    }

    // Sort posts by date (newest first)
    blogPosts.sort((a, b) => new Date(b.date) - new Date(a.date))

    // Generate the TypeScript file content
    const tsContent = `export interface BlogPost {
  title: string
  excerpt: string
  date: string
  readTime: string
  category: string
  slug: string
  content: string
  tags: string[]
}

export const blogPosts: BlogPost[] = [
${blogPosts
  .map(
    (post) => `  {
    slug: "${post.slug}",
    title: "${post.title}",
    excerpt: "${post.excerpt}",
    date: "${post.date}",
    readTime: "${post.readTime}",
    category: "${post.category}",
    tags: ${JSON.stringify(post.tags)},
    content: \`${post.content}\`,
  }`,
  )
  .join(",\n")}
]
`

    // Write the generated content to lib/blog-posts.tsx
    await writeFile("lib/blog-posts.tsx", tsContent, "utf-8")

    console.log(`[v0] Successfully generated lib/blog-posts.tsx with ${blogPosts.length} posts`)
    console.log("[v0] Blog posts generation completed!")
  } catch (error) {
    console.error("[v0] Error generating blog posts:", error)
  }
}

// Run the generator
generateBlogPosts()
